import PAGE from "../../../utils/middleware/page";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import store from "../../../store/index";
const app = getApp();
Page(PAGE({
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            needRefresh: 'vehicle.needRefresh'
        },
        actions: {
            updateNeedNavigate: 'vehicle.updateNeedNavigate',
            updateNeedNavigatePage: 'vehicle.updateNeedNavigatePage'
        }
    },
    data: {
        tabIndex: 0,
        parkInfo: {},
        apiField: {
            module: 'common',
            api: 'GetPark',
            data: 'parkInfo',
            search: {
                parkId: null
            }
        },
    },
    onLoad(options) {
        this.data.apiField.search.parkId = options.parkId
        this.fetchData()
    },
    async fetchData() {
        this.handleFetchData({}, 'apiField', true)
    },
    async submitForm(e) {
         var _this = this
        const params = e.detail.value
        if (!params.CardNumber) {
            wx.$Fun.showToast('10位数字卡号不能为空')
            return
        }
        if (this.data.tabIndex == 1 && !params.Phone) {
            wx.$Fun.showToast('手机号不能为空')
            return
        }
        try {
            var req = {
                cardNumber: params.CardNumber,
                parkId: this.data.apiField.search.parkId
            }
            var method = 'Add'
            if (this.data.tabIndex == 1) {
                method = "HelpAdd"
                req.MemberPhone = params.Phone
            }

            var res = await wx.$Api.powerCard[method]({
                data: req
            })

            if (res.Data.PayAmount > 0) {
                //发起支付
                const prePayRes = await wx.$Api.payment.PrePay({ data: { tradeNo: res.Data.TradeNo } })
                console.log('支付参数', prePayRes)
                wx.$Fun.wxPay(prePayRes.Data).then(resp => {
                    _this.bindSuccess()
                }).catch(e => {
                    console.log(e)
                })
            }
            else {
                this.bindSuccess()
            }
        }
        catch (e) {
            wx.$Fun.showToast(e.Message)
        }
    },
    handleTabChange(e) {
        var index = e.currentTarget.dataset.index
        this.setData({
            tabIndex: index
        })
    },
    bindSuccess() {
        //返回到首页并跳转到套餐列表页面
        this.updateNeedNavigate(true)
        this.updateNeedNavigatePage('powerCardList')
        wx.navigateBack({
            delta: 4
        })
    }
}));
